<template>
  <div class="clearfix login-out">
    <div class="login-logo clearfix">
      <img src="../../assets/images/logo.png">
    </div>
    <div class="login-mid clearfix">
      <div class="login-con fxr clearfix">
              <div class="top-font clearfix">
                祝融赛事平台登陆系统
              </div>
        <el-form
            class="form-icon clearfix"
            ref="formData"
            :model="formData"
            :rules="rules"
            label-width="0px"
            @submit.native.prevent="submitForm">
          <el-tabs v-model="activeName" class="tab-radius" @tab-click="handleClick">
            <el-tab-pane label="帐号密码登录" name="1">
              <div class="clearfix" v-if="activeName==1">
                <el-form-item label="" prop="username">
                  <i class="iconfont icon-yonghuming"></i>
                  <el-input
                      v-model="formData.username"
                      placeholder="请输入用户名"
                  ></el-input>
                </el-form-item>
                <el-form-item label="" prop="password">
                  <i class="iconfont icon-mima"></i>
                  <el-input
                      type="password"
                      v-model="formData.password"
                      placeholder="请输入密码"
                  ></el-input>
                </el-form-item>
                <el-form-item label="" prop="captcha">
                  <i class="iconfont icon-yanzhengma"></i>
                  <img class="pos-abs r-img" :src="formData.randCodeImage" @click="randomImage"/>
                  <el-input
                      class="fxl"
                      v-model="formData.captcha"
                      placeholder="请输入验证码"
                  ></el-input>
                </el-form-item>
              </div>
            </el-tab-pane>
            <el-tab-pane label="手机验证码登录" name="2">
              <div class="clearfix" v-if="activeName==2">
                <el-form-item prop="phone">
                  <i class="iconfont icon-shoujihao"></i>
                  <el-button type="text" class="r-img pos-abs" :disabled="showFont" @click="getSms(2,1)" style="margin:0px 10px 0px 0px;">
                    <span v-if="!showFont">获取验证码</span>
                    <span v-else><b class="time-num">{{timeCount}}</b>后可重新获取</span>
                  </el-button>
                  <el-input type="text" placeholder="请输入手机号" v-model="formData.phone" />
                </el-form-item>
                <el-form-item label="" prop="phoneCaptcha">
                  <i class="iconfont icon-mima"></i>
                  <el-input type="text" placeholder="请输入手机验证码" v-model="formData.phoneCaptcha" />
                </el-form-item>
              </div>

            </el-tab-pane>
          </el-tabs>
          <el-button type="primary" class="login-submit" native-type="submit">登&nbsp;&nbsp;录</el-button>
          <span class="fxl" style="line-height:30px;">还没有注册？</span>
          <el-button class="fxl" type="text" @click="openDialog(1)">立即注册</el-button>
          <el-button class="fxr" type="text" @click="openDialog(2)">忘记密码？</el-button>
        </el-form>
      </div>
    </div>

    <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="510"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
        :before-close="handleClose">
      <div class="clearfix" style="padding-right:20px;">
        <el-form v-if="dialogVisible"
            ref="openFormRef"
            :model="openForm"
            :rules="openRules"
            label-width="auto"
            status-icon>
          <el-form-item label="用户名" v-if="dialogStatic==1" prop="username">
            <el-input type="text" placeholder="请输入用户名" v-model="openForm.username" />
          </el-form-item>
          <div class="clearfix">
            <el-form-item :label="dialogStatic==2?'短信验证码':'手机号'" required>
              <el-col :span="15">
                <el-form-item prop="phone">
                  <el-input type="text" placeholder="请输入手机号" v-model="openForm.phone" />
                </el-form-item>
              </el-col>
              <el-col :span="1"> </el-col>
              <el-col :span="8">
                <el-button class="fxr" type="primary" @click="getSms(dialogStatic==1?1:3,2)" :disabled="showFont">
                  <span v-if="!showFont">获取验证码</span>
                  <span v-else><b class="time-num" style="color:#fff">{{timeCount}}</b>后可重新获取</span>
                </el-button>
              </el-col>
            </el-form-item>
            <el-form-item label="验证码" prop="smscode">
              <el-input type="text" placeholder="请输入短信验证码" v-model="openForm.smscode" />
            </el-form-item>
            <el-form-item :label="dialogStatic==2?'新密码':'密码'" prop="newPwd">
              <el-input type="password" :placeholder="dialogStatic==2?'请输入新密码':'请输入密码'" v-model="openForm.newPwd" />
            </el-form-item>
            <el-form-item :label="dialogStatic==2?'新密码确认':'密码确认'" prop="affirmPassword">
              <el-input type="password" :placeholder="dialogStatic==2?'请输入新密码':'请输入密码'" v-model="openForm.affirmPassword" />
            </el-form-item>
          </div>

        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelOpen">取消</el-button>
          <el-button type="primary" @click="openSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
let initData = null;
export default {
  data() {
    return {
      timeCount:60,
      showFont:false,
      timer:null,
      dialogVisible:false,
      dialogTitle:'',
      activeName: '1',
      dialogStatic:1,//1:注册  2:忘记密码
      formData: {
        randCodeImage: null,
        username: "",
        captcha: "",
        password: "",
        phoneCaptcha:'',
        checkKey: "12345",
      },
      smsStatic:false,
      openForm:{
        confirmpassword:'',
        phonePass:'',
        newPwd:'',
        smscode:'',
        affirmPassword:'',
        phone:'',
        phonePassword:'',
      },
      openRules:{
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3456789]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
        ],
        newPwd: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 6, message: '密码长度最少6字符', trigger: 'blur' }
          // { pattern:/^(?=.*[a-zA-Z])(?=.*\d)(?=.*[~!@#$%^&*()_+`\-={}:";'<>?,./]).{8,}$/, message: '密码由8位数字、大小写字母和特殊符号组成!', trigger: 'blur' }
        ],
        smscode:[
          {required: true, message: '请输入验证码', trigger: 'blur'},
        ],
        affirmPassword: [
          {required: true, message: '请确认密码', trigger: 'blur'},
          {min: 6, message: '密码长度最少6字符', trigger: 'blur' }
          // { pattern: /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[~!@#$%^&*()_+`\-={}:";'<>?,./]).{8,}$/, message: '密码由8位数字、大小写字母和特殊符号组成!', trigger: 'blur' }
        ],
        phoneCaptcha:[
          {required: true, message: '请确认手机验证码', trigger: 'blur'},
        ]
      },
      rules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
        ],
        password: [
          {required: true, message: '请输入输入密码', trigger: 'blur'},
          // { pattern: /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[~!@#$%^&*()_+`\-={}:";'<>?,./]).{8,}$/, message: '密码由8位数字、大小写字母和特殊符号组成!', trigger: 'blur' }
        ],
        captcha: [
          {required: true, message: '请输入验证码', trigger: 'blur'},
        ],
        phone: [
          {required: true, message: '请输入手机号', trigger: 'blur'},
          { pattern: /^1[3456789]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
        ],
        phonePassword: [
          {required: true, message: '请输入手机号验证码', trigger: 'blur'},
        ],
      },
      menuData:[],
    };
  },

  inject: ["imageUrl", "serviceUrl"],

  mounted() {
    window.sessionStorage.clear()
    window.localStorage.clear()
    this.randomImage()
  },
  created() {
    initData = {
      formData: JSON.stringify(this.formData),
      openForm: JSON.stringify(this.openForm)
    };
  },
  methods: {
    openDialog(num){
      console.log(num);
      clearInterval(this.timer);
      this.showFont = false;
      this.openForm = JSON.parse(initData.openForm);
      switch (num){
        case 1:
          this.dialogTitle = '注册'
          break;
        case 2:
          this.dialogTitle = '忘记密码'
          break;
      }
      this.dialogVisible = true
      this.dialogStatic = num
    },
    reg() {
      this.$router.push("/register");
    },
    cancelOpen(){
      clearInterval(this.timer);
      this.showFont = true;
      this.dialogVisible = false
    },
    handleClick() {

    },
    openSubmit(){
      if(this.openForm.newPwd!==this.openForm.affirmPassword){
        this.$message.warning('两次密码不一致，请重新输入！')
        return
      }
      this.$refs["openFormRef"].validate((valid) => {
        if (valid) {
          if(this.dialogStatic==1){
            axios
                .post(this.serviceUrl + "/sys/user/register", {
                  password: this.openForm.newPwd,
                  phone: this.openForm.phone,
                  smscode: this.openForm.smscode,
                  username: this.openForm.username
                })
                .then((resp) => {
                  if (resp.data.code==200) {
                    this.$message.success(resp.data.message);
                    this.dialogVisible = false
                    this.$router.push("/login");
                  } else {
                    this.$message.error(resp.data.message);
                  }
                })
                .catch((error) => {
                  //console.log(error);
                });
          }else if(this.dialogStatic==2){
            axios
                .post(this.serviceUrl + "/sys/user/changePasswordBySmsCode", {
                  confirmpassword:this.openForm.affirmPassword,
                  password: this.openForm.newPwd,
                  phone: this.openForm.phone,
                  smscode: this.openForm.smscode,
                })
                .then((resp) => {
                  if (resp.data.code==200) {
                    this.$message.success(resp.data.message);
                    this.dialogVisible = false
                    this.$router.push("/login");
                  } else {
                    this.$message.error(resp.data.message);
                  }
                })
                .catch((error) => {
                  //console.log(error);
                });
          }
        }
      });
      clearInterval(this.timer);
      this.showFont = true;
    },
    handleClose(){
      this.dialogVisible = false
    },
    randomImage() {
      axios
          .get(this.serviceUrl + "/sys/randomImage", {
            params: {_t: new Date().getTime()},
          })
          .then((resp) => {
            this.formData.randCodeImage = resp.data.result;
          })
          .catch((error) => {
            //console.log(error);
          });
    },
    submitForm() {
      console.log('aaa');
      let url,params={}
      this.$refs['formData'].validate((valid) => {
        switch (this.activeName){
          case '1':
            url = '/sys/login';
            params = {
              username:this.formData.username,
              password:this.formData.password,
              captcha:this.formData.captcha
            }
            break;
          case '2':
            url = '/sys/phoneLogin';
            params = {
              phone:this.formData.phone,
              smscode:this.formData.phoneCaptcha
            }
            break;
        }
        console.log(url,params);
        if (valid) {
          axios
              .post(this.serviceUrl + url, params)
              .then((resp) => {
                console.log(resp);
                if (resp.data.success) {
                  localStorage.setItem("token", resp.data.result.token);
                  localStorage.setItem(
                      "userInfo",
                      JSON.stringify(resp.data.result.userInfo)
                  );
                  this.getMenu(resp.data.result.userInfo)
                  // this.$router.push("/pc");
                } else {
                  this.$message.error(resp.data.message);
                  this.randomImage()
                  this.formData.captcha = ""
                }
              })
              .catch((error) => {
                //console.log(error);
              });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    getSms(num,open){
      this.timer = null
      //1 注册  2 登录  3 忘记密码
      if(((num==1||num==3)&&(this.openForm.phone==''||!this.openForm.phone))||(num==2&&(this.formData.phone==''||!this.formData.phone))){
        this.$message.warning('请输入手机号！')
        return
      }
      axios
          .post(this.serviceUrl + "/sys/sms", {
            phone:open==2?this.openForm.phone:this.formData.phone,
            smsmode:num==1?1:2
          })
          .then((resp) => {
            if(resp.data.code==500){
              this.smsStatic = true
              this.$message.warning(resp.data.message);
            }else if(resp.data.code==200||resp.data.code==0){
              this.smsStatic = false
              this.timeCount = 60
              if (!this.timer) {
                this.showFont = false
                this.timer = setInterval(() => {
                  this.showFont = true
                  if (this.timeCount > 0 && this.timeCount <= 60) {
                    this.timeCount--;
                  } else {
                    clearInterval(this.timer);
                    this.showFont = false;
                    this.timer = null;
                  }
                }, 1000);
              }
            }

          })
          .catch((error) => {

          });
    },
    getMenu(params){
      let that = this;
      axios
          .get(that.serviceUrl + "/sys/user/queryUserRole2", {
            headers: {
              "X-Access-Token": localStorage.getItem("token"),
            },
            params: {
              userid: params.id,
              _t: new Date().getTime(),
            },
          })
          .then((resp) => {
            if (resp.data.success) {
              if (resp.data.result.includes("cansr")) {
                this.menuData = this.menuData.concat([
                  { title: "首页", icon: "icon-shouye", url: "/pc/home" },
                  {
                    title: "我的参赛作品",
                    icon: "icon-wodezuopin",
                    url: "/pc/canszp_saisxz",
                  },
                ]);
              }

              if (resp.data.result.includes("zilsh")) {
                this.menuData = this.menuData.concat([
                  {
                    title: "资料审核",
                    icon: "icon-zhiliangpingshen",
                    url: "/pc/zilsh_saisxz",
                  },
                ]);
              }

              if (resp.data.result.includes("pingw")) {
                this.menuData = this.menuData.concat([
                  {
                    title: "赛事评审",
                    icon: "icon-shejipingshen",
                    url: "/pc/saisps_saisxz",
                  },
                ]);
              }

              if (resp.data.result.includes("jinjqr")) {
                this.menuData = this.menuData.concat([
                  {
                    title: "晋级确认",
                    icon: "icon-jjqr",
                    url: "/pc/jinjqr_saisxz",
                  },
                ]);
              }

              if (resp.data.result.includes("fuh")) {
                this.menuData = this.menuData.concat([
                  { title: "复核", icon: "icon-pingshen", url: "/pc/fuh_saisxz" },
                ]);
              }

            }

            if(this.menuData.length>0){
              localStorage.setItem("menuSelect",'0')
              localStorage.setItem("menuData", JSON.stringify(this.menuData));
              this.$router.push(this.menuData[0].url);
            }else{
              this.$message.warning('无菜单权限，请联系管理员！')
            }
            console.log(this.menuData,'this.menuData');
          })
          .catch((error) => {
            //console.log(error);
          });
    }
  },
};
</script>
<style lang="less" scoped>
.login-out {
  background: linear-gradient(to left, #f5271b 0%, #E90D00 100%);
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  .login-mid {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    width:1080px;
    height:600px;
    background:url(../../assets/images/loginBg.png) no-repeat left center;
    background-size:auto 100%;

  }

  .login-con {
    width: 390px;
    background: #fff;
    box-shadow: 0px 0px 20px rgba(0, 0, 0, 0.11);
    padding: 50px 40px;
    border-radius: 5px;
  }

  .top-font {
    padding: 0px 0px 30px 0px;
    font-size: 28px;
    font-weight: bold;
    width:100%;
    text-align: center;
  }

  .login-submit {
    width: 100%;
    background: linear-gradient(to left, #E90D00 0%, #E90D00 100%);
    font-size: 16px;
    font-weight: bold;
    padding: 15px;
    height: auto;
    border: 0px;
    //box-shadow: 0px 5px 10px rgba(233, 13, 0, 0.42);
    margin: 10px 0px 20px 0px;
  }
}

.form-icon {
  .el-form-item {
    margin-bottom: 25px;
  }

  .el-form-item__content {
    display: block;
    position: relative;

    i {
      position: absolute;
      z-index: 10;
      left: 20px;
      top: 8px;
      font-size: 18px;
      color: #E90D00;
      opacity: .5;
    }

    .r-img {
      z-index: 10;
      right: 8px;
      top: 7px;
      height: 34px;
      border-radius: 50px;
    }

    .el-input {
      background: #F9F9F9;
      padding: 8px 10px 8px 40px;
      border:1px solid #DCDEE2;

      :deep(.el-input__wrapper) {
        background: transparent !important;
        font-size: 16px;
        box-shadow: 0px 0px 0px #000;
      }
    }
  }

  :deep(.el-form-item__error) {
    padding: 5px 0px 0px 50px;
    text-align: left;
    font-size: 14px;
  }
}
.time-num{
  color:#E90D00;
  font-size:18px;
  margin:0px 2px 0px 0px;
  font-weight: bold;
}
.login-logo{
  position: absolute;
  top: 5%;
  left: 5%;
  img{
    height:100px;
  }
}
:deep(.el-button--text){
  color:#E90D00 !important;
}
:deep(.el-tabs__item:hover){
  color:#E90D00 !important;
}
@media screen and (max-width: 1200px) {
  .login-out .login-mid{
    background:url(../../assets/images/loginBg.png) no-repeat bottom center;
    background-size:auto auto;
    height:100%;
  }
  .login-out .login-mid{
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .login-out .login-con{
    width:560px;
    margin-bottom:400px;
  }
}
</style>
